package mauth

import (
	"github.com/gin-gonic/gin"
	"mygo/mymongo"
	"mygo/mystruct"
	"mygo/myws"
	"mygo/mylog"
	"mygo/global"
	"strings"
)

// token获取
func Get_token(c *gin.Context) *mystruct.Muser {
	UserNameBoot := c.GetHeader("UserNameBoot")

	var Muserboot *mystruct.Muser
	if UserNameBoot != "" {
		Muserboot = mymongo.Get_Chcae_User(UserNameBoot, global.Mtoken.Key)
		if Muserboot == nil {
			mesg := myws.Mesg{
				Type: "Login",
				Code: 1002,
				Msg: "登录已失效",
			}
			go myws.SendWs(mesg)
			mylog.MyLog(mesg, c.Request.RemoteAddr, global.Mtoken.Log_Path)
			c.JSON(mystruct.StatusPaymentRequired, gin.H{"error": "登录失效"})
			c.Abort()
			return nil
		}
	}
	if Muserboot == nil {
		Muserboot = &mystruct.Muser{
			Name: "游客",
			Account: "",
			Standing: mystruct.AUTH_Tourist,
		}
	}
	return Muserboot
}

func GetClientIP(cont *gin.Context) string {
    ip := cont.Request.Header.Get("X-Real-IP")
    if ip == "" {
        ips := cont.Request.Header.Get("X-Forwarded-For")
        if ips != "" {
            ip = strings.Split(ips, ",")[0] // 取第一个IP
        }
    }
    if ip == "" {
        ip = cont.ClientIP()
    }
    return ip
}